import PublicApi from "@/common/api/form/public.js";
import {exportExcel}  from './ExcelExport.js';
import FormExcelTemplateApi from "@/common/api/form/formExcelTemplate";
import FormPrintLodopApi from "@/common/api/form/formPrintLodop";
import useMain from "@/stores/useMain.js";
import { mapState } from 'pinia';
import FormWordTemplateApi from "@/common/api/form/formWordTemplate";
import {I18Parse,TokenUtil} from '@lowcode/jpaas-base-lib';
import formbaseApi from '@/language/lang/impl/form/formBaseApiLang';

let lang = formbaseApi;
let i18n=function (langKey,text) {
    return I18Parse.getI18Val(lang.formBaseApi,langKey, text)
}
/**
 * 打印公共处理方法
 */
export default {
    data() {
        return {
            lodopUtil:{}
        }
    },
    computed: {
        ...mapState(useMain, [ 'appKey','curApp']),
    },
    methods: {
        printI18(name,text,key){
            return this.$ti18(name,text,"formBaseApi",key);
        },
        /**
         * 打印
         */
        print(btn) {
            let formBuild=this.getFormVm();
            let dataJson = formBuild.data;
            let url =import.meta.env.JPAAS_BASE_URL+"/"+this.appKey+"/formPrint/" + this.formSolution.alias;
            let pk=this.pkId || this.formPkId
            if (pk) {
                url += "/" + pk;
            }
            let appId=this.curApp.appId;
            if(!appId){
                appId = this.$route.query.appId;
            }
            url+="?appId="+ appId;
            window['_getFormData_'+this.formSolution.alias]=function(){
                return dataJson;
            }
            window.formSolutionName=this.formSolution.name;
            window.open(url);
        },
        /**
         * ureport打印
         * @param btn
         */
        async ureportPrint(btn) {
            let formBuild=this.getFormVm();
            let json = formBuild.data;
            if (!json.ID_) {
                this.$message.warning(i18n('funcJs.useUreport','编辑状态才能使用报表!!'));
                return;
            }
            //获得当前编辑数据的ID
            let btnConf=btn.conf;
            let parameter="";
            for (let item of btnConf.params) {
                if (item.returnValue){
                    if (item.valueSource=="param"){
                        //表单字段映射
                        let paramName=item.returnValue;
                        paramName=paramName.toLowerCase();
                        parameter+= '&'+item.bindFieldLabel + '=' + json[paramName] ;
                    }else if (item.valueSource=="constantlet "){
                        //常量
                        let paramMap=[]
                        paramMap.push({name:item.bindFieldLabel,valueSource:item.valueSource,valueDef:item.returnValue})
                        //调用方法替换常量值
                        let rtn=await PublicApi.getParams(JSON.stringify(paramMap))
                        if (rtn){
                            parameter+= '&'+item.bindFieldLabel + '=' + rtn[item.bindFieldLabel] ;
                        }
                    }else if (item.valueSource=="fixedlet "){
                        //固定值
                        parameter+= '&'+item.bindFieldLabel + '=' + item.returnValue ;
                    }else {
                        parameter+="";
                    }
                }

            }
            let url = "/ureport/preview?_u=qiaolin-" + btnConf.name + "&Id=" + json.ID_+parameter;
            var token=TokenUtil.getToken();
            if(token){
                url += "&accessToken="+token;
            }
            window.open(url);
        },

        /**
         * 套打。
         * @param btn
         */
        async printLodop(btn) {
            let defId=btn.config.defId;
            if (!defId) {
                this.$message.warning(i18n('funcJs.printLodopTips','编辑状态才能打印!'));
                return;
            }
            this.lodopUtil = (await import('./LodopFuncs.js')).default;
            let formBuild=this.getFormVm();
            let json = formBuild.data;
            this.lodopUtil.onload(function(lodop){
                if (!lodop) {
                    return;
                }
                //初始化任务名称
                lodop.PRINT_INIT(btn.config.name);
                FormPrintLodopApi.printHtml({
                    pkId: defId,
                    formData: JSON.stringify(json)
                }).then(res => {
                    eval(res.data);
                    //打印预览
                    lodop.PREVIEW();
                })
            })
        },

        /**
         * Excel打印
         * @param btn
         */
        excelPrint(btn) {
            let formBuild=this.getFormVm();
            btn.loading = true;
            let self = this;
            let formData=formBuild.data;
            let boDefId= btn.config.boDefId;
            let title=formBuild.name;
            let templateId=btn.config.templateId;
            if(!btn.config.templateId){
                self.$notification['warning']({message: self.$ti18('rxMsa.actionTips', '操作提示'),
                    description:i18n('msa.excelPrintTips','未绑定模板!'),});
                return;
            }
            this.$confirm({
                content: i18n('msa.excelPrintConfirm','您确定要将当前表单打印成excel吗?'),
                zIndex: 40000,
                okText: this.$ti18('rxForm.ackBtn', '确认'),
                cancelText: this.$ti18('rxForm.cancelBtn', '取消'),
                onOk() {
                    //打印当前excel 表单别名与表单数据
                    FormExcelTemplateApi.excelPrint({boDefId:boDefId,formData:JSON.stringify(formData),templateId:templateId}).then(res=>{
                        if(res && res.data){
                            btn.loading = false;
                            exportExcel(res.data,title);
                        }else {
                            self.$notification['error']({
                                message: self.$ti18('rxMsa.actionTips', '操作提示'),
                                description:i18n('msa.printError','生成失败!'),
                            });
                            btn.loading = false;
                            return;
                        }
                    });
                },
                onCancel() {
                    btn.loading = false;
                }
            });
        },
        /**
         * Excel对话框
         * @param btn
         */
        excelDialog(btn) {
            let self = this;
            let boDefId= btn.config.boDefId;
            let templateId=btn.config.templateId;
            if(!btn.config.templateId){
                self.$notification['warning']({message:  self.$ti18('rxMsa.actionTips', '操作提示'),
                    description:i18n('msa.excelPrintTips','未绑定模板!'),});
                return;
            }
            let obj={ pkId:self.formData[self.idField],alias:this.formSolution.alias ,boDefId:boDefId,templateId:templateId };
            let params= window.btoa(encodeURIComponent(JSON.stringify(obj)));
            let appId=this.curApp.appId;
            if(!appId){
                appId = this.$route.query.appId;
            }
            let url = `/luckyExcel/preview?params=${params}&appId=${appId}`;
            window['formData_'+this.formSolution.alias]=self.formData;
            window.open(url,"_blank");
        },
        //Word打印
        wordPrint(btn) {
            let formBuild=this.getFormVm();
            btn.loading = true;
            let self = this;
            let formData=formBuild.data;
            let boDefId= btn.config.boDefId;
            let formName=formBuild.name;
            let templateId=btn.config.templateId;
            if(!btn.config.templateId){
                self.$notification['warning']({message:  self.$ti18('rxMsa.actionTips', '操作提示'),
                    description:this.printI18('msa.wordPrintTips','未绑定word模板!'),});
                return;
            }
            this.$confirm({
                content: this.printI18('msa.wordPrintConfirm','您确定要将当前表单打印成Word吗?'),
                zIndex: 40000,
                okText: this.$ti18('rxForm.ackBtn', '确认'),
                cancelText: this.$ti18('rxForm.cancelBtn', '取消'),
                onOk() {
                    //打印当前word 表单别名与表单数据
                    FormWordTemplateApi.wordPrint({boDefId:boDefId,formData:JSON.stringify(formData),single:true,templateId:templateId}).then(res=>{
                        if(!res){
                            self.$notification['error']({
                                message:  self.$ti18('rxMsa.actionTips', '操作提示'),
                                description:this.printI18('msa.wordPrintError','生成Word失败!'),
                            });
                            btn.loading = false;
                            return;
                        }
                        let blob = new Blob([res], {
                            type: 'application/vnd.ms-word'
                        });
                        let fileName = formName + '.docx';
                        if (window.navigator.msSaveOrOpenBlob) {
                            navigator.msSaveBlob(blob, fileName);
                        } else {
                            let link = document.createElement('a');
                            link.href = window.URL.createObjectURL(blob);
                            link.download = fileName;
                            link.click();
                            //释放内存
                            window.URL.revokeObjectURL(link.href)
                        }
                        btn.loading = false;
                    });
                },
                onCancel() {
                    btn.loading = false;
                }
            });
        },
    }
}
